package com.javabase.y2022.m04.day0420.v0021;

/**
 * @descriptions:
 * @author: Tom
 * @date: 2022/4/20 下午 01:37
 * @version: 1.0
 */
public class Solution {
    static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public static void main(String[] args) {
        Solution so = new Solution();
        ListNode l1 = new ListNode();
        ListNode l2 = new ListNode();

        l1.val = 1;
        l1.next = new ListNode();
        l1.next.next = new ListNode();
        l1.next.val = 2;
        l1.next.next.val = 4;
        l2.next = new ListNode();
        l2.next.next = new ListNode();
        l2.val = 1;
        l2.next.val = 3;
        l2.next.next.val = 4;
        ListNode l3 = so.mergeTwoLists(l1, l2);
        while (l3 != null) {
            System.out.print("  " + l3.val);
            l3 = l3.next;
        }

    }

    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode prehead = new ListNode(-1);
        ListNode pre = prehead;
        while(list1 != null && list2 != null){
            if(list1.val < list2.val){
                pre.next = list1;
                list1 = list1.next;
            }else{
                pre.next = list2;
                list2 = list2.next;
            }
            pre = pre.next;
        }
        pre.next = list1 == null ? list2: list1;
        return prehead.next;
    }
}
